package com.sx.gongzhong.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.MyApplication;
import com.sx.gongzhong.R;
import com.sx.gongzhong.adapter.CommentListAdapter;
import com.sx.gongzhong.adapter.ImageAdapter;
import com.sx.gongzhong.adapter.viewholder.HelpHeadView;
import com.sx.gongzhong.model.CommentBean;
import com.sx.gongzhong.model.HelpBean;
import com.sx.gongzhong.model.MsgEvent;
import com.sx.gongzhong.net.MyRxBus;
import com.sx.gongzhong.net.ServiceFactory;
import com.sx.gongzhong.pest.HelpDetailPest;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.HelpDetailView;
import com.sx.gongzhong.widget.CustomDialog;
import com.sx.gongzhong.widget.LoadDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 互帮互助详情
 */
public class HelpDetailActivity extends BaseActivity implements View.OnClickListener, HelpDetailView {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.et_Comment)
    EditText etComment;
    @BindView(R.id.rl_et_comment)
    RelativeLayout rlEtComment;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;

    private String helpId;
    private int page = 1, pageSize = 5;
    private HelpBean detailBean;

    private List<CommentBean> mlist;
    private CommentListAdapter commentListAdapter;
    private TextView praise, tv_State;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.recy_edit);
        ButterKnife.bind(this);
        setTitleName("互帮互助详情");
        setRightImage(R.mipmap.icon_nav_more);
        LoadDialog.show(HelpDetailActivity.this);
        helpId = getIntent().getStringExtra("helpId");
        new HelpDetailPest(this).getHelpDetail(helpId);
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(HelpDetailActivity.this);
        ToastUtils.showToast(HelpDetailActivity.this, message);
        if (message.equals("获取详情失败")) {
            finish();
        }
    }

    @Override
    public void getHelpDetailSuccess(HelpBean data) {
        LoadDialog.dismiss(HelpDetailActivity.this);
        detailBean = data;
        initView();
        getCommentData();
    }

    private void initView() {
        mlist = new ArrayList<>();
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(false);
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        commentListAdapter = new CommentListAdapter(this, R.layout.item_commont_list, mlist);
        commentListAdapter.setColumnType("help_each_other_reply");
        if (detailBean.getPublisher() != null){
            commentListAdapter.setPublishUserId(detailBean.getPublisher().getId());
            if (MyApplication.instance.userBean != null) {
                if (MyApplication.instance.userBean.id.equals(detailBean.getPublisher().getId())) {
                    commentListAdapter.setHost(true);
                }
            }
        }
        View view = View.inflate(this, R.layout.no_comment_view, null);
        TextView tv_Hint = (TextView) view.findViewById(R.id.tv_hint);
        tv_Hint.setText("暂无答复");
        commentListAdapter.setHeaderAndEmpty(true);
        commentListAdapter.setEmptyView(view);
        commentListAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
                getCommentData();
            }
        }, recyclerView);
        View headView = LayoutInflater.from(this).inflate(R.layout.head_help_view, null);
        commentListAdapter.addHeaderView(headView);
        recyclerView.setAdapter(commentListAdapter);

        HelpHeadView helpHeadView = new HelpHeadView();
        ButterKnife.bind(helpHeadView, headView);
        praise = helpHeadView.tv_Praise;
        if (detailBean.getPublisher() != null) {
            helpHeadView.tv_Name.setText(detailBean.getPublisher().getName());
            RequestOptions options = new RequestOptions().centerCrop()
                    .placeholder(R.mipmap.img_head_default)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .circleCrop()
                    .error(R.mipmap.img_head_default);
            Glide.with(this)
                    .load(ServiceFactory.getUrl(detailBean.getPublisher().getHeaderUrl()))
                    .apply(options)
                    .into(helpHeadView.im_Head);
        }
        tv_State = helpHeadView.tv_State;
        if (detailBean.getHandleStatus().equals("to_be_solved")) {
            tv_State.setText("待解决");
            commentListAdapter.setVisiAdopt(true);
            tv_State.setBackgroundResource(R.drawable.shape_red_corner_50);
            rlEtComment.setVisibility(View.VISIBLE);
        } else if (detailBean.getHandleStatus().equals("shut_down")) {
            tv_State.setText("已关闭");
            commentListAdapter.setVisiAdopt(false);
            tv_State.setBackgroundResource(R.drawable.shape_orige_corner_50);
            rlEtComment.setVisibility(View.GONE);
        } else if (detailBean.getHandleStatus().equals("solved")) {
            tv_State.setText("已解决");
            commentListAdapter.setVisiAdopt(false);
            tv_State.setBackgroundResource(R.drawable.shape_green_corner_50);
            rlEtComment.setVisibility(View.GONE);
        }

        helpHeadView.tv_Time.setText(detailBean.getReleaseTime());
        helpHeadView.tv_Praise.setText(detailBean.getPraiseTimes());
        helpHeadView.tv_Preview.setText(detailBean.getReadTimes());
        helpHeadView.tv_Content.setText(detailBean.getContent());

        if (detailBean.getFiles() != null && detailBean.getFiles().size() > 0) {
            ImageAdapter adapter = new ImageAdapter(this, R.layout.item_image, detailBean.getFiles());
            helpHeadView.imgListView.setAdapter(adapter);
        }
        helpHeadView.tv_Praise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLogin()) {
                    if (!isParise) {
                        new HelpDetailPest(HelpDetailActivity.this).addHelpPraise(helpId);
                    } else {
                        ToastUtils.showToast(HelpDetailActivity.this, "已点过赞");
                    }
                }
            }
        });
        etComment.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (isLogin()) {
                    if (keyCode == event.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                        if (etComment.getText().toString().trim().length() == 0) {
                            ToastUtils.showToast(HelpDetailActivity.this, "请输入内容");
                            return false;
                        }
                        new HelpDetailPest(HelpDetailActivity.this).addComment(helpId, etComment.getText().toString().trim());
                        return true;
                    }
                }
                return false;
            }
        });
    }

    private void getCommentData() {
        new HelpDetailPest(this).getHelpCommentList(helpId, page, pageSize);
    }

    @Override
    public void getHelpCommentListSuccess(List<CommentBean> rows, int total) {
        if (page == 1) {
            mlist.clear();
            commentListAdapter.setNewData(mlist);
        }
        if (rows != null && rows.size() > 0) {
            mlist.addAll(rows);
        }
        if (page == total) {
            commentListAdapter.loadMoreEnd();
        } else {
            commentListAdapter.loadMoreComplete();
        }
        commentListAdapter.notifyDataSetChanged();
    }

    @Override
    public void addCommentSuccess(CommentBean commentBean) {
        etComment.setText(" ");
        page = 1;
        getCommentData();
    }

    @Override
    public void addHelpPraiseSuccess(Integer data) {
        ToastUtils.showToast(HelpDetailActivity.this, "点赞成功");
        isParise = true;
        praise.setText(data + "");
    }

    @Override
    public void closeHelpSuccess(Boolean data) {
        detailBean.setHandleStatus("undelte");
        tv_State.setText("已关闭");
        tv_State.setBackgroundResource(R.drawable.shape_orige_corner_50);
        rlEtComment.setVisibility(View.GONE);
    }

    @Override
    public void deleteHelpSuccess(Boolean data) {
        LoadDialog.dismiss(HelpDetailActivity.this);
        ToastUtils.showToast(HelpDetailActivity.this, "删除成功");
        MyRxBus.get().post(new MsgEvent("HelpActivity", 1, null));
        finish();
    }

    private boolean isParise = false;

    @OnClick({R.id.imv_Right})//
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imv_Right:
                if (isLogin()) {
                    String handstatus = detailBean.getHandleStatus();
                    if ("to_be_solved".equals(handstatus)) {//待解决 可以关闭 删除
                        handstatus = "help_can_close_delete";
                    }/*else {//其他状态 不可删除
                        handstatus = "undelte";
                    }*/
                    if (detailBean.getPublisher() != null){
                        createPop(detailBean.getPublisher().getId(), handstatus);
                    }
                }
                break;
            case R.id.tv_Close://关闭
                popupWindow.dismiss();
                createDialog(1, "关闭");
                break;
            case R.id.tv_ShutUp://整个诉求禁言
                popupWindow.dismiss();
                createDialog(2, "禁言");
                break;
            case R.id.tv_Report://举报楼主
                popupWindow.dismiss();
                createDialog(3, "举报");
                break;
            case R.id.tv_Delete://删除诉求
                popupWindow.dismiss();
                createDialog(4, "删除");
                break;
            case R.id.tv_Cancel:
                popupWindow.dismiss();
                break;
        }
    }

    /**
     * 删除/举报/关闭/采纳
     */
    public void createDialog(final int type, String title) {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        CustomDialog dialog = builder.setMessage("确定" + title + "吗？").
                setBackButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setConfirmButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (type == 1) {
                    new HelpDetailPest(HelpDetailActivity.this).closeHelp(helpId);
                } else if (type == 2) {
                    createReport("forbiddenType", detailBean.getId(), "help_each_other");
                } else if (type == 3) {
                    createReport("reportType", detailBean.getId(), "help_each_other");
                } else if (type == 4) {
                    LoadDialog.show(HelpDetailActivity.this, "删除中...");
                    new HelpDetailPest(HelpDetailActivity.this).deleteHelp(helpId);
                }
            }
        }).create();
        dialog.show();
    }

    public void adpotSuccess() {
        detailBean.setHandleStatus("solved");
        if (tv_State != null) {
            tv_State.setText("已解决");
            tv_State.setBackgroundResource(R.drawable.shape_green_corner_50);
        }
        rlEtComment.setVisibility(View.GONE);
    }

}
